<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArtList">筛选</el-button>
            <el-button type="info" size="small" @click="artReset">重置</el-button>
          </el-form-item>
        </el-form>

        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" >
          <template #default='{row}'>
            <el-link type='primary' @click="showDetail(row.id)">{{row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template #default='{row}'>
            {{row.pub_date | dateFormat}}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template #default='{row}'>
             <el-button type="danger" size="mini" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域
        current-page: 当前页码值
        page-size: 每页显示的条数
        total: 总条数
        page-sizes: 动态设置每页显示的条数
        layout: 分页的布局

        @size-change:每页条数改变时触发
        @current-change: 页码值改变时触发
       -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-size="q.pagesize"
        :page-sizes="[2, 3, 5, 10]"
        layout="total, sizes,  prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 发布文章的弹出框 -->
    <el-dialog
      title="发布文章"
      :visible.sync="pubVisible"
      fullscreen
      :before-close="handleBeforeClose"
      @close="handleClose"
    >
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
          <!-- 标题 -->
        <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请填写文章标题"></el-input>
        </el-form-item>
          <!-- 分类 -->
        <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择文章分类" style="width: 100%;">
                <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
        </el-form-item>
        <!-- 内容 -->
        <el-form-item label="文章内容">
            <quill-editor v-model="pubForm.content"></quill-editor>
        </el-form-item>

        <!-- 封面 -->
        <el-form-item label="文章封面">
            <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="onChange"/>
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
        </el-form-item>

        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="clickSubmit('已发布')">发布</el-button>
          <el-button type="info" @click="clickSubmit('草稿')">存草稿</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!-- 文章详情弹出框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
       <h1>{{artDetail.title}}</h1>
        <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ artDetail.pub_date | dateFormat }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <el-divider></el-divider>

       <!-- 文章的封面 -->
      <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>

import defaultImg from '@/assets/images/cover.jpg'

export default {
  name: 'ArtList',
  created () {
    this.getArtCateList()

    this.getArtList()
  },
  data () {
    return {
      q: {
        pagenum: 1, // 页码值
        pagesize: 2, // 每页显示条数
        cate_id: '', // 分类id
        state: '' // 文章状态
      },

      total: 0,

      pubVisible: false,

      // 文章表单
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章分类', trigger: 'blur' }
        ]
      },

      //  分类列表
      cateList: [],

      // 文章列表
      artList: [],

      // 文章详情数据
      artDetail: {},

      // 文章详情是否显示
      detailVisible: false
    }
  },
  methods: {
    async handleBeforeClose (done) {
      const result = await this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (result === 'cancel') return

      // 关闭弹出框
      done(true)
    },

    // 获取文章分类数据
    async getArtCateList () {
      const { data: res } = await this.$http.get('/my/cate/list')
      this.cateList = res.data
    },

    // 选择封面
    chooseImg () {
      this.$refs.iptFile.click()
    },

    // input type=file 的 change事件(以前没有图片,现在选择了一张图片会触发)
    onChange (e) {
      // e.target.files[0] 封面图片对象  axios发送时 传的数据就是它
      const files = e.target.files
      if (files.length === 0) {
        this.pubForm.cover_img = null
      } else {
        //   选择了图像
        // 需求:预览 (1.FileReader  2.URL)
        // 2.URL.createObjectURL()
        const url = URL.createObjectURL(files[0])
        // console.log(url) // blob:http://localhost:8080/ce0b1534-60f2-40e6-892f-eb34c045d75e
        this.$refs.imgRef.src = url
        this.pubForm.cover_img = files[0]
      }
    },

    // 处理弹出框关闭
    handleClose () {
      // 清除校验表单项
      this.pubVisible = false
      this.$refs.pubFormRef.resetFields()

      this.pubForm.content = ''
      this.pubForm.cover_img = null
      this.pubForm.state = ''
      this.$refs.imgRef.src = defaultImg
    },

    // 存文章
    clickSubmit (type) {
      // 设置文章类型
      this.pubForm.state = type

      // 校验表单
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid) return
        if (this.pubForm.content === '') return this.$message.error('请填写文章内容')
        if (this.pubForm.cover_img === null) return this.$message.error('请设置文章封面图片')

        // 将数据追加到formData中
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }

        console.log(fd)
        // fd.forEach((item) => {
        //   console.log(item)
        // })

        // axios发送请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        // 1.关闭发表文章的弹出框
        this.handleClose()

        // 2.todo: 重新获取文章列表
        this.getArtList()
      })
    },

    // 获取文章列表
    async getArtList () {
      const { data: res } = await this.$http.get('/my/article/list', { params: this.q })
      this.artList = res.data
      this.total = res.total
    },

    // 处理条数改变
    handleSizeChange (newSize) {
      // 1.重置每页显示的条数
      this.q.pagesize = newSize
      // 2.再次获取文章列表数据
      this.q.pagenum = 1
      this.getArtList()
    },
    // 处理页码改变时
    handleCurrentChange (newPage) {
      // 1.重置页码值
      this.q.pagenum = newPage
      // 2.再次获取文章列表数据
      this.getArtList()
    },

    // 文章列表重置功能
    artReset () {
      this.q = {
        cate_id: '',
        state: '',
        pagenum: 1,
        pagesize: 2
      }
      // 重新获取文章的数据(变为初始状态)
      this.getArtList()
    },

    // 显示文章详情
    async showDetail (id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      this.artDetail = res.data

      // 显示文章详情弹出框
      this.detailVisible = true
    },

    // 根据id删除文章
    async del (id) {
      const result = await this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (result === 'cancel') return

      const { data: res } = await this.$http.delete('/my/article/info', { params: { id: id } })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)

      // 判断当前页是否只有一条数据,并且不是第1页
      if (this.artList.length === 1 && this.q.pagenum > 1) this.q.pagenum--
      // 重新获取数据
      this.getArtList()
    }
  }
}
</script>

<style scoped lang='less'>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

::v-deep .ql-editor {
  min-height: 200px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination{
  margin-top:20px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
